package com.design.classroommanagement.admin

import com.alibaba.android.arouter.facade.annotation.Route
import com.design.classroommanagement.Pages
import com.design.classroommanagement.api.Bookmark
import com.design.classroommanagement.api.dao.BookmarkDao
import com.design.classroommanagement.databinding.FragmentAddCourseBinding
import com.design.classroommanagement.setBack
import com.design.classroommanagement.setTitleClassRoom
import com.laughing.lib.base.BaseFragmentNoVM
import com.laughing.lib.utils.arguments
import com.laughing.lib.utils.clickWithTrigger
import com.laughing.lib.utils.runInBg
import kotlinx.android.synthetic.main.fragment_add_course.*

@Route(path = Pages.AddCourseFragment)
class AddCourseFragment : BaseFragmentNoVM<FragmentAddCourseBinding>() {
    private var isUpdate: Boolean = false
    val bookmarkValue = arguments<Bookmark>("data")

    override fun initCompleted() {
        binding.submitBtn.clickWithTrigger {
            submit()
        }
        setTitleClassRoom("添加课程信息")
        setBack()
        render()
    }

    fun render() {
        val bookmark = bookmarkValue.value
        isUpdate = bookmark != null

        nameEt.setText(bookmark?.name)
        teacherEt.setText(bookmark?.tid)
        classroomEt.setText(bookmark?.classname)
        timeEt.setText(bookmark?.date)
        if (isUpdate) {
            setTitleClassRoom("更新课程信息")
            submitBtn.text = "更新"
        }
    }

    fun submit() {
        val bookmark = (bookmarkValue.value ?: Bookmark()).apply {
            name = nameEt.text.toString()
            tid = teacherEt.text.toString()
            classname = classroomEt.text.toString()
            date = timeEt.text.toString()
        }

        runInBg {
            if (isUpdate) {
                BookmarkDao.update(bookmark)
            } else {
                BookmarkDao.add(bookmark)
            }
            finish()
        }
    }
}